package com.hydra.gateway.utils;

import com.hydra.base.error.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import reactor.util.annotation.NonNull;

/**
 * 获取Spring容器的Bean对象的工具类
 * @Author Hydra
 * @Date 2022/3/17 18:05
 */
@Slf4j
@Component
public class SpringUtils implements ApplicationContextAware  {

    protected static ApplicationContext CONTEXT;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        if (null == CONTEXT) {
            throw new BusinessException("The application context is null, please check.");
        } else {
            return CONTEXT.getBean(name);
        }
    }

    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        if (null == CONTEXT) {
            throw new BusinessException("The application context is null, please check.");
        } else {
            return CONTEXT.getBean(requiredType);
        }
    }

    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        if (null == CONTEXT) {
            throw new BusinessException("The application context is null, please check.");
        } else {
            return CONTEXT.getBean(name, requiredType);
        }
    }

}
